package com.guoran100.adphoto.display.util;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.support.v7.app.AlertDialog;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.guoran100.adphoto.application.MyApplication;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;


import java.io.File;

import im.fir.sdk.FIR;
import im.fir.sdk.VersionCheckCallback;

/**
 * Created by caomenglong on 16/7/29.
 */
public class ToolsUtils {

    public static String TAG="ToolsUtils";

    public static void checkUpdate(final Activity activity){



        FIR.checkForUpdateInFIR(MyApplication.FIRAPITOKEN , new VersionCheckCallback() {
            @Override
            public void onSuccess(String versionJson) {
                Log.i(TAG,"check from fir.im success! " + "\n" + versionJson);
                JSONObject json = JSON.parseObject(versionJson);
                checkUpdateAction(json,activity);
            }

            @Override
            public void onFail(Exception exception) {
                Log.i(TAG, "check fir.im fail! " + "\n" + exception.getMessage());
            }

            @Override
            public void onStart() {
                Log.i(TAG, "正在获取");
            }

            @Override
            public void onFinish() {
                Log.i(TAG, "获取完成");
            }
        });



    }


    //开始执行更新判断
    private static void checkUpdateAction(JSONObject json,final Activity activity){
        int versionCode=Integer.parseInt(json.getString("version"));
        String versionName=json.getString("versionShort");
        String installUrl=json.getString("installUrl");
        String changelog=json.getString("changelog");

        try {
            // ---get the package info---
            PackageManager pm = MyApplication.getAppContext().getPackageManager();
            PackageInfo pi = pm.getPackageInfo(MyApplication.getAppContext().getPackageName(), 0);
            String currentVersionName = pi.versionName;
            int currentversionCode = pi.versionCode;
            Log.d(TAG,currentVersionName+"  "+currentversionCode);

            if(currentversionCode<versionCode){
                Log.d(TAG,"需要更新");
                UpdateChecker updateChecker=new UpdateChecker(activity,installUrl,changelog);
                updateChecker.showUpdateDialog();

            }else{
                ToastUtils.with(activity).show("当前版本是最新版本!");
                Log.d(TAG,"不需要更新");
            }

        } catch (Exception e) {
            Log.e(TAG, "Exception", e);
        }



    }

    public static void checkNetwork(Activity activity){
        //如果没有网络可用就退出程序
        if (ToolsUtils.isConnect(activity)==false)
        {
            new AlertDialog.Builder(activity)
                    .setTitle("网络错误")
                    .setMessage("网络连接失败，请确认网络连接")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {

                            android.os.Process.killProcess(android.os.Process.myPid());
                            System.exit(0);
                        }
                    })
                    .setCancelable(false)
                    .show();
        }
    }

    //检查网络是否正常
    public static boolean isConnect(Context context) {
        // 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
        try {
            ConnectivityManager connectivity = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivity != null) {
                // 获取网络连接管理的对象
                NetworkInfo info = connectivity.getActiveNetworkInfo();
                if (info != null&& info.isConnected()) {
                    // 判断当前网络是否已经连接
                    if (info.getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            Log.v("error",e.toString());
        }
        return false;
    }




}

//下载类
class UpdateChecker{
    Activity activity;
    String downURL="";
    String changeLog="";
    private ProgressDialog mProgressDialog;

    private File apkFile;

    public UpdateChecker(Activity activity,String Url,String changelog){
        this.activity= activity;
        this.downURL=Url;
        this.changeLog=changelog;
        mProgressDialog = new ProgressDialog(activity);
        mProgressDialog.setMessage("正在下载");
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setCancelable(true);
        mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {

            }
        });
        mProgressDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                // TODO Auto-generated method stub

            }
        });
    }


    //显示下载提示框
    public void showUpdateDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        //builder.setIcon(R.drawable.ic_heart);
        builder.setTitle("有新版本");
        builder.setMessage(this.changeLog);
        builder.setPositiveButton("下载",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        downLoadApk();
                    }
                });
        builder.setNegativeButton("忽略",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                    }
                });
        builder.setCancelable(false);
        builder.show();
    }

    //开始执行下载
    public void downLoadApk(){
        String dir = activity.getExternalFilesDir("apk").getAbsolutePath();
        File folder = Environment.getExternalStoragePublicDirectory(dir);
        if(folder.exists() && folder.isDirectory()) {
            //do nothing
        }else {
            folder.mkdirs();
        }
        Log.d("ToolsUtils",dir);
        Log.d("ToolsUtils",downURL);
        long currentTime = System.currentTimeMillis();
        final String path=dir+"/shiguo365"+Long.toString(currentTime)+".apk";
        Log.d("ToolsUtils",path);
        apkFile = new File(path);
        mProgressDialog.show();
        FileDownloader.getImpl().create(downURL)
                .setPath(path)
                .setListener(new FileDownloadListener() {
                    @Override
                    protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        Log.d("ToolsUtils","pending"+String.valueOf(soFarBytes));
                    }

                    @Override
                    protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {
                        Log.d("ToolsUtils","connected");
                    }

                    @Override
                    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        double value1=((double)soFarBytes/(double)totalBytes);
                        int value2=(int)(value1*100);
                        mProgressDialog.setProgress(value2);
                    }

                    @Override
                    protected void blockComplete(BaseDownloadTask task) {
                        Log.d("ToolsUtils","blockComplete");
                    }

                    @Override
                    protected void retry(final BaseDownloadTask task, final Throwable ex, final int retryingTimes, final int soFarBytes) {
                        Log.d("ToolsUtils","retry");
                    }

                    @Override
                    protected void completed(BaseDownloadTask task) {
                        Log.d("ToolsUtils","completed");
                        mProgressDialog.setProgress(100);
                        mProgressDialog.dismiss();
                        String[] command = {"chmod","777",apkFile.toString()};
                        try{
                            ProcessBuilder builder = new ProcessBuilder(command);
                            builder.start();
                            //运行程序
                            Intent intent = new Intent(Intent.ACTION_VIEW);
                            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
                            activity.startActivity(intent);
                        }catch (Exception e){

                        }

                    }

                    @Override
                    protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        Log.d("ToolsUtils","paused");
                    }

                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {
                        Log.d("ToolsUtils","error");
                    }

                    @Override
                    protected void warn(BaseDownloadTask task) {
                        Log.d("ToolsUtils","warn");
                    }
                }).start();
    }

}


